package com.teemor.blog.service.impl;


import com.teemor.blog.bean.condition.TbArticleCondition;
import com.teemor.blog.bean.condition.TbIprecordCondition;
import com.teemor.blog.bean.dto.output.BaseInfo;
import com.teemor.blog.bean.entity.TbIprecord;
import com.teemor.blog.bean.enums.ArticleStates;
import com.teemor.blog.mapper.TbArticleMapper;
import com.teemor.blog.mapper.TbIprecordMapper;
import com.teemor.blog.service.IIprecordService;
import com.teemor.common.bean.utils.IPInfoUtils;
import com.teemor.common.bean.utils.enums.DataStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
  * @author: zhoulk
  * @Description: 原子服务实现
  * @date: 2020/03/19 20:59:38
 */
@Service
public class IprecordServiceImpl implements IIprecordService {

    @Autowired
    private TbIprecordMapper tbIprecordMapper;
    @Autowired
    private TbArticleMapper tbArticleMapper;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public int countIprecord(TbIprecordCondition condition) {
        return tbIprecordMapper.countIprecordByCondition(condition);
    }

    @Override
    public List<TbIprecord> qryIprecords(TbIprecordCondition condition) {

        return tbIprecordMapper.selectIprecordByCondition(condition);
    }

    @Override
    public TbIprecord qryIprecordById(Integer id) {
        return tbIprecordMapper.selectIprecordById(id);
    }

    @Override
    public int addIprecord(TbIprecord inParam) {
        inParam.setAddr(IPInfoUtils.getIpaddr(restTemplate, inParam.getIp()));
        return tbIprecordMapper.insertIprecord(inParam);
    }

    @Override
    public int updIprecordById(TbIprecord inParam) {
        return tbIprecordMapper.updateIprecordById(inParam);
    }

    @Override
    public BaseInfo qryBaseInfo() {
        BaseInfo baseInfo = new BaseInfo();
        baseInfo.setBrowserNum(tbIprecordMapper.countIprecordByCondition(new TbIprecordCondition()));
        TbArticleCondition tbArticleCondition = new TbArticleCondition();
        tbArticleCondition.setDataState(DataStatus.USE.value());
        tbArticleCondition.setAtcState(ArticleStates.PUBLISH.value());
        baseInfo.setArticleNum(tbArticleMapper.countArticleByCondition(tbArticleCondition));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date old = simpleDateFormat.parse("2019-6-1");
            Date now = new Date();
            long r1 = now.getTime() - old.getTime();
            baseInfo.setRunDays(r1 / (24 * 60 * 60 * 1000));
        } catch (ParseException e) {
            baseInfo.setRunDays(800L);
        }
        return baseInfo;
    }
}